<template>
    <div>
        <Button @click="runSql()">运行全部</Button>
        <Button>运行选择的</Button>
        <Input @ v-model="sqlString" type="textarea" :rows="6" placeholder="Enter something..." />
        <Table size="small" border :columns="table_head" :data="table_data"></Table>
    </div>
</template>

<script>

    var mysql = require('mysql');
    var connection;
    export default {
        name: "table-search",
        data () {
            return {
                sqlString : "",
                table_head: [],
                table_data: []

            }
        },
        methods: {
            initConnect() {
                connection = mysql.createConnection({
                    host: 'localhost',
                    port: 3306,
                    user: 'root',
                    password: '123456',
                    database: "gnerv-business"
                });
            },
            runSql() {
                this.initConnect();
                connection.connect();
                var _this = this;
                var sql = _this.sqlString;
                connection.query(sql, function (err, result) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    if(result.length > 0) {
                        _this.table_head = [];
                        let j = {};
                        j.type = 'selection';
                        j.width = 50;
                        j.align = 'center';
                        _this.table_head.push(j);
                        for (var i = 0; i < 1; i++) {
                            let keys = Object.keys(result[i]);
                            for (let key of keys) {
                                let j = {};
                                j.title = key;
                                j.key = key;
                                _this.table_head.push(j);
                            }
                        }
                        _this.table_data = [];
                        for (let obj of result) {
                            _this.table_data.push(obj);
                        }
                    }
                });
                connection.end();
            }
        },
        created : function() {
            this.initConnect();
        }
    }
</script>

<style scoped>

</style>